<?php

namespace backend\models;

use backend\services\AdminMenuService;
use backend\services\AdminUserService;
use Yii;
use yii\web\IdentityInterface;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;


class BackendUser extends ActiveRecord implements IdentityInterface
{
    private $_menus;

    private $rightUrls;

    /**
     */
    public static function validatePassword($user, $password)
    {
        return ($user != null && Yii::$app->getSecurity()->validatePassword($password, $user->password));
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public static function login($username, $password, $rememberMe)
    {
        $user = self::findByUsername($username);
        if (self::validatePassword($user, $password) == true && $user->status == AdminUserService::$STATUS_USABLE) {
            if (Yii::$app->user->login($user, $rememberMe ? 3600 * 24 * 30 : 0) == true) {
//                $user->initUserModuleList();
                $user->initUserModuleList2();
                $user->initUserUrls();
                return true;
            }
        }
        return false;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return self::findOne([
            'uname' => $username,
            'status' => AdminUserService::$STATUS_USABLE
        ]);
    }

    public static function findIdentity($id)
    {
        return self::findOne([
            'id' => $id,
            'status' => AdminUserService::$STATUS_USABLE
        ]);

    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * cookie
     *
     * @see \yii\web\IdentityInterface::getId()
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * cookie登录需要实现
     *
     * @see \yii\web\IdentityInterface::getAuthKey()
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * cookie登录需要实现
     *
     * @see \yii\web\IdentityInterface::getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public function initUserModuleList2()
    {
        $systemMenuService = new AdminMenuService();
        $urlList = $systemMenuService->getUserModuleList2($this->id);
        $modules = [];
        $menus = [];
        foreach ($urlList as $key => $_url) {
            if ($_url['type'] == AdminMenuService::$TYPE_MODULE) {
                $modules[] = [
                    'id' => $_url['id'],
                    'label' => $_url['name'],
                    'ico'=>$_url['ico'],
                    'url' => $_url['entry_url']
                ];
            } else if ($_url['type'] == AdminMenuService::$TYPE_MENU) {
                $menus[$_url['pid']][] = [
                    'id' => $_url['id'],
                    'label' => $_url['name'],
                    'ico'=>$_url['ico'],
                    'url' => $_url['entry_url']
                ];
            }
        }
        foreach ($modules as $key => $module) {
            $id = $module['id'];
            $module['funcList'] = $menus[$id];
            $modules[$key] = $module;
        }

        $this->_menus = $modules;
        Yii::$app->session['system_menus_' . $this->id] = $modules;
        return $modules;
    }

    public function initUserUrls($userId = 0)
    {
        // 获取所有权限
        $rights = AdminRoleUser::find()->alias('role')
            ->select(['menu.menu_id','menu.role_id'])
            ->leftJoin('admin_role_menu menu','role.role_id = menu.role_id')
            ->where(['role.user_id'=>$this->id])
            ->asArray()
            ->all();
        // 取出所有权限和权限链接(没有区分权限)
        $menus = AdminMenu::find()->select(['id','pid','entry_url','type','name'])
            ->where(['or',['type'=>AdminMenuService::$TYPE_RIGHT_URL],['type'=>AdminMenuService::$TYPE_RIGHT]])
//            ->where(['type'=>SystemMenuService::$TYPE_RIGHT_URL])
            ->asArray()
            ->all();
        $menu_rights = [];
        foreach($menus as $menu){
            if($menu['type'] == AdminMenuService::$TYPE_RIGHT){
                $menu_rights[$menu['id']]['right'] = $menu;
            }
            else if($menu['type'] == AdminMenuService::$TYPE_RIGHT_URL){
                $menu_rights[$menu['pid']]['urls'][] = $menu;
            }
        }
        $right_data = [];
        foreach ($rights as $right_temp) {
            $right_id = $right_temp['menu_id'];
            $menu_right = $menu_rights[$right_id];
            $right = $menu_right['right'];
            if(empty($menu_right['urls']) == false){
                $urls = $menu_right['urls'];
                foreach($urls as $url_temp){
                    $entry_url = $url_temp['entry_url'];
                    $paras = explode('/', $entry_url);
                    $right_data[$entry_url] = [
                        "urlid"=>$right['id'],
                        "url"=>$entry_url,
                        "para_name"=>$paras[0],
                        "para_value"=>$paras[1],
//                        "role_id"=>$url_temp['role_id'],
                        "right_id"=>$url_temp['id'],
                        "right_name"=>$right['name'],
                        "entry_url"=>$entry_url,
                        "menu_name"=>"",
                        "module_name"=>""
                    ];
                }
            }

        }
//        exit(json_encode($right_data));
        Yii::$app->session['system_rights_' . $this->id] = $right_data;
        return $right_data;
    }


    public function getSystemMenus()
    {
        if (isset(Yii::$app->session['system_menus_' . $this->id]) == false) {
            //$this->initUserModuleList();
            $this->initUserModuleList2();
        }
        return Yii::$app->session['system_menus_' . $this->id];
    }

    public function getSystemRights()
    {
        if (isset(Yii::$app->session['system_rights_' . $this->id]) == false) {
            $this->initUserUrls();
        }
        return Yii::$app->session['system_rights_' . $this->id];
    }

    public function clearUserSession()
    {
        Yii::$app->session['system_menus_' . $this->id] = null;
        Yii::$app->session['system_rights_' . $this->id] = null;
    }
}

?>